<?php
declare (strict_types=1);

namespace app\controller;


use app\BaseController;
use app\common\Printer;
use app\common\UserService;
use app\job\Task;
use app\model\AdminMoneyLog;
use app\model\GoodsOrders;
use app\model\PointGoodsOrders;
use app\model\PuddleOrders;
use app\model\User;
use app\model\Vip;
use app\model\VipOption;
use app\model\VipOrders;
use app\tool\Http;
use app\traits\Response;
use think\facade\Log;
use think\facade\Queue;
use Yansongda\Pay\Pay;

class NotifyController extends BaseController
{
	use Response;
	
	
	function returnNotify()
	{
		
		$paytype = $this->request->param('paytype');
		$config = config('pay');
		switch ($paytype) {
			case 'wechat':
				$pay = Pay::wechat($config);
				try {
					$res = $pay->callback();
				} catch (\Exception $e) {
					$this->writeJson(0, '验签错误');
				}
				$res = $res->resource;
				$res = $res['ciphertext'];
				$out_trade_no = $res['out_trade_no'];
				$attach = $res['attach'];
				break;
			case 'alipay':
				$pay = Pay::alipay($config);
				try {
					$res = $pay->callback();
				} catch (\Exception $e) {
					$this->writeJson(0, $e->getMessage());
				}
				$out_trade_no = $res->out_trade_no;
				$attach = $res->passback_params;
				break;
			case 'balance':
				$out_trade_no = $this->request->param('out_trade_no');
				$attach = $this->request->param('attach');
				break;
			default:
				$this->writeJson(0, '支付类型错误');
		}
		
		switch ($attach) {
			case 'goods':
				$order = GoodsOrders::where(['order_sn' => $out_trade_no, 'pay_status' => 1])->find();
				if (!$order) {
					$this->writeJson(0, '订单不存在');
				}
				
				$order->pay_status = 2;
				$order->paytime = time();
				$order->save();
				$num = 0;
				foreach ($order->detail as $detail) {
					$num += $detail->num;
					$detail->goods->sales += 1;
					$detail->together(['goods'])->save();
				}
				AdminMoneyLog::create([
					'user_id' => $order->user_id,
					'type' => 1,
					'mark' => "购买了{$num}件商品",
					'amount' => $order->pay_amount,
					'num' => $num,
				]);
				$address = \app\model\Config::getFieldByName('address', 'value');
				//发送短信
				$username = '13592592467';
				$password = md5('lfl123456' . date('Y-m-d H:i:s'));
				$smscontent = "【美人港垂钓园】您已成功购买商品，订单号为{$out_trade_no}，领取地点：{$address}。";
				Http::post('http://api.sms1086.com/Api/Sendutf8.aspx', [
					'username' => $username,
					'password' => $password,
					'content' => $smscontent,
					'mobiles' => $order->user->mobile,
					'timestamp' => date('Y-m-d H:i:s'),
					'f' => '1'
				]);
				
				$content = "<FS2><center>--在线支付--</center></FS2>";
				$content .= "<FS><center>现金商城</center></FS>";
				$content .= "订单时间:". $order->createtime . "\n";
				$content .= "订单编号:".$order->order_sn."\n";
				$content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
				$content .= "<table>";
				foreach ($order->detail as $detail){
					$content .= "<tr><td>{$detail->goods->name}</td><td>x{$detail->num}</td><td>{$detail->amount}</td></tr>";
				}
				$content .= "</table>";
				$content .= str_repeat('.', 32);
				$content .= "提货人:{$order->take_delivery->name} \n";
				$content .= "联系方式:{$order->take_delivery->mobile} \n";
				$content .= "小计:￥".$order->total_amount."\n";
				$content .= "折扣:￥".$order->coupon_amount." \n";
				$content .= str_repeat('*', 32);
				$content .= "订单总价:￥".$order->pay_amount." \n";
				$content .= "<FS2><center>**# 完**</center></FS2>";
				Printer::print('4004869429',$content,$order->order_sn);
				break;
			case 'point_goods':
				$order = PointGoodsOrders::where(['order_sn' => $out_trade_no, 'pay_status' => 1])->find();
				if (!$order) {
					$this->writeJson(0, '订单不存在');
				}
				$order->pay_status = 2;
				$order->paytime = time();
				$order->save();
				foreach ($order->detail as $detail) {
					$detail->goods->sales += 1;
					$detail->together(['goods'])->save();
				}
				$address = \app\model\Config::getFieldByName('address', 'value');
				//发送短信
				$username = '13592592467';
				$password = md5('lfl123456' . date('Y-m-d H:i:s'));
				$smscontent = "【美人港垂钓园】您已成功兑换商品，订单号为{$out_trade_no}，领取地点：{$address}。";
				Http::post('http://api.sms1086.com/Api/Sendutf8.aspx', [
					'username' => $username,
					'password' => $password,
					'content' => $smscontent,
					'mobiles' => $order->user->mobile,
					'timestamp' => date('Y-m-d H:i:s'),
					'f' => '1'
				]);
				
				//58mm排版 排版指令详情请看 http://doc2.10ss.net/332006
				$content = "<FS2><center>--在线支付--</center></FS2>";
				$content .= "<FS><center>积分商城</center></FS>";
				$content .= "订单时间:". $order->createtime . "\n";
				$content .= "订单编号:".$order->order_sn."\n";
				$content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
				$content .= "<table>";
				foreach ($order->detail as $detail){
					$content .= "<tr><td>{$detail->goods->name}</td><td>x{$detail->num}</td><td>{$detail->amount}</td></tr>";
				}
				$content .= "</table>";
				$content .= str_repeat('.', 32);
				$content .= "提货人:{$order->take_delivery->name} \n";
				$content .= "联系方式:{$order->take_delivery->mobile} \n";
				$content .= "小计:".$order->pay_amount."积分\n";
				$content .= "折扣:0积分 \n";
				$content .= str_repeat('*', 32);
				$content .= "订单总价:".$order->pay_amount."积分 \n";
				$content .= "<FS2><center>**# 完**</center></FS2>";
				Printer::print('4004869429',$content,$order->order_sn);
				break;
			case 'vip':
				$order = VipOrders::where(['order_sn' => $out_trade_no, 'pay_status' => 1])->find();
				if (!$order) {
					$this->writeJson(0, '订单不存在');
				}
				$vipoption = VipOption::findOrFail($order->option_id);
				$user = User::findOrFail($order->user_id);
				$paytime = time();
				$order->pay_status = 2;
				$order->paytime = $paytime;
				$order->save();
				
				
				if ($user->vip_expiretime ?? 0 <= time()) {
					//VIP已过期
					$user->vip_expiretime = strtotime("+ {$vipoption->month} month", $paytime);
				} else {
					$user->vip_expiretime = strtotime("+ {$vipoption->month} month", $user->vip_expiretime);
				}
				$user->level = $vipoption->vip->id;
				$user->save();
				
				AdminMoneyLog::create([
					'user_id' => $order->user_id,
					'type' => 2,
					'mark' => "开通了{$vipoption->month}个月会员",
					'amount' => $order->pay_amount,
					'num' => $vipoption->month,
				]);
				
				//更改会员状态
				Queue::later($user->vip_expiretime - $paytime, Task::class, ['user_id' => $user->id, 'action' => 'vip_expire'], 'task');
				
				Queue::later($user->vip_expiretime - $paytime - 60 * 60 * 24 * 7, Task::class, ['user_id' => $user->id, 'action' => 'vip_expire_warn'], 'task');
				//返点
				if ($user->parent) {
					$ratio_amount = $vipoption->ratio;
					UserService::changeUserMoney($ratio_amount, $user->parent->id, '下级开通VIP返利');
				}
				break;
			case 'puddle':
				$order = PuddleOrders::where(['order_sn' => $out_trade_no, 'pay_status' => 1])->find();
				if (!$order) {
					$this->writeJson(0, '订单不存在');
				}
				$paytime = time();
				$order->pay_status = 2;
				$order->paytime = $paytime;
				$order->save();
				
				//发送短信
				$username = '13592592467';
				$password = md5('lfl123456' . date('Y-m-d H:i:s'));
				$content = "【美人港垂钓园】您已成功预约钓位，订单号为{$out_trade_no}。";
				Http::post('http://api.sms1086.com/Api/Sendutf8.aspx', [
					'username' => $username,
					'password' => $password,
					'content' => $content,
					'mobiles' => $order->user->mobile,
					'timestamp' => date('Y-m-d H:i:s'),
					'f' => '1'
				]);
				break;
			default:
				$this->writeJson(0, '回调错误');
		}
		
		return match ($paytype) {
			'wechat', 'alipay' => $pay->success(),
			'balance' => true,
			default => $this->writeJson(0, '支付类型错误'),
		};
		
	}
	
}
